package com.fuerda.izb.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.fuerda.izb.R

class PercentageRectView : View {
    private var paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var colorBlockPercentage = 0f // 色块百分比，范围从0到100

    constructor(context: Context) : super(context) {
        init(null, 0)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(attrs, defStyleAttr)
    }

    private fun init(attrs: AttributeSet? = null, defStyleAttr: Int = 0) {
        val typedArray = context.obtainStyledAttributes(
            attrs,
            R.styleable.PercentageRectView,
            defStyleAttr,
            0
        )

        colorBlockPercentage =
            typedArray.getInt(R.styleable.PercentageRectView_colorBlockPercentage, 0)
                .toFloat() / 100
        typedArray.recycle()

        paint.color = Color.WHITE // 设置色块颜色
        paint.style = Paint.Style.FILL
    }

    fun setColorBlockPercentage(percentage: Int) {
        if (percentage in 0..100) {
            this.colorBlockPercentage = percentage.toFloat() / 100
            invalidate() // 请求重绘
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val width = width.toFloat()
        val height = height.toFloat()

//        // 绘制整个View的背景（可选）
//        paint.color = Color.GRAY
//        canvas.drawRect(0f, 0f, width, height, paint)

        // 根据百分比计算色块的长度
        val colorBlockWidth = width * colorBlockPercentage
        val colorBlockRect = RectF(0f, 0f, colorBlockWidth, height)

        canvas.drawRect(colorBlockRect, paint)
    }
}